package com.demo.io.nio;

import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * 请求处理
 *
 * @author lee9213@163.com
 * @version 1.0
 * @date 2017/3/20 18:05
 */
public class ProcessJob implements Runnable {

    private Selector clientSelector;

    public ProcessJob(Selector clientSelector) {
        this.clientSelector = clientSelector;
    }

    @Override
    public void run() {
        int count = 0;
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        try {
            while (true) {
                int n = clientSelector.selectNow();
                if (n <= 0) continue;
                Iterator<SelectionKey> iterator = clientSelector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    SocketChannel client = (SocketChannel) selectionKey.channel();
                    while ((count = client.read(byteBuffer)) > 0) {
                        System.out.write(byteBuffer.array(), 0, count);
                        byteBuffer.clear();
                    }
                    client.close();
                }
                iterator.remove();

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
